<?php

class ModuleFunctionAction extends Action {
    
	
	/**
	 * @param  $type--keyword/page
	 */
    public function getFunctionList($type,$order="updateTime", $orderBy="desc", $start=0, $limit=25){
    	
    	$ModuleFunction = D("module_function");
    	
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    	
    	$cid = Session::$user["customerId"];
    	
    	$condition['function.type'] = array('eq',$type);
    	$condition['function.deleted'] = array('eq',0);
//     	$condition['cmgroup.customerId'] = array('eq',$cid);
//     	$condition['cmgroup.permission'] = array('eq','allow');
//     	$condition['mgroup.display'] = array('eq','0');
    	
    	$sql="select distinct mgroup.group  from wx_module_group mgroup 
				LEFT JOIN wx_customer_module_group cmgroup on cmgroup.group=mgroup.group";
    	$arr = $ModuleFunction->alias("function")
    			->join("INNER JOIN ($sql) as msgroup on msgroup.group = function.group")
//     			->join("LEFT JOIN (select )wx_module_group mgroup on mgroup.group=function.group")
    			->where($condition)
    			->field("function.*")
    			->order("$order $orderBy")
    			->limit("$start, $limit")
    			->select();
    	if($arr){
    		$count =  $ModuleFunction->alias("function")
    			->join("LEFT JOIN ($sql) as msgroup on msgroup.group = function.group")
//     			->join("LEFT JOIN (select )wx_module_group mgroup on mgroup.group=function.group")
    			->where($condition)->count();
    		
    		Output::instance()->objArray($arr,$count);
    	}else{
    		Output::instance()->resultCode(code_success);
    	}
    }
    
    
    public function getModuleFunctionByType($content,$type){
    	$ModuleFunction = D("module_function");
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    	$cid = Session::$user["customerId"];
    	
    	if($type == 'view'){
//     		$content = urldecode($content);
    		$queryParts = explode('&', $content);
    		$urlparams = array();
    		$paramsItems = array();
    		foreach ($queryParts as $param){
    			$item = explode('=', $param);
    			$urlparams[$item[0]] = $item[1];
    		}
    		$module = $urlparams['module'];
    		$method = $urlparams['method'];
    		$params = $urlparams['params'];
    		$params = str_replace( array('%7B','%7D','%22'), array('','',''), $params);
    		$params = str_replace(array('{', '}', '"'), array('','',''), $params);
    		$queryParams = explode(',', $params);
    		foreach ($queryParams as $par) {
    			$item = explode(':', $par);
    			$paramsItems[$item[0]] = $item[1];
    		}
    		
    		$fcondition['module'] = array('eq',$module);
    		$fcondition['method'] = array('eq',$method);
    		$function = $ModuleFunction->where($fcondition)->find();
//     		echo $ModuleFunction->getLastSql();
    		if($function) {
    			switch($module){
    				case 'webPage':
    					$result = $this->getWebPage($method, $paramsItems['id']);
    					break;
    				case 'webSite':
    					$result = $this->getWebSite($method, $paramsItems['id']);
    					break;
    				case 'product':
    					$result = $this->getProduct($method, $paramsItems);
    					break;
    				case 'store':
    					$result = $this->getStore($method, $paramsItems);
    					break;
    				case 'mall':
    				case 'fortuneWheel':
    				case 'questionnaire':
    				case 'collectInformation':
    					$result = $this->getModuleMaterial($paramsItems['id']);
    					break;
    				case 'vote':
    					$result = $this->getModuleMaterial($paramsItems['mid']);
    					break;
    				case 'greetingCard':
    					$result = $this->getGreetingCard($method, $paramsItems['id']);
    					break;
    				case 'expertQA':
    					$result = $this->getExpertQA($method);
    					break;
    				case 'member':
    					$result = $this->getMember($method, $paramsItems['cid']);
    					break;
    				case 'employeeManage':
    					$result = $this->getEmployeeManage($method);
    					break;
    			}
    			
    			if (empty($result)) {
    				$result['fName'] = NULL;
    				$result['fId'] = NULL;
    			}
    			$function = array_merge($function, $result);
     			Output::instance()->object($function);
    		} else {
    			Output::instance()->resultCode(code_success);
    		}
    	}else if($type == 'click'){//关键字
    		
    		$keyarr = explode(',',$content);
    		
    		if(count($keyarr) > 0){
    			$condition['function.deleted'] = array('eq',0);
    			$condition['keyword.keyword'] = array('eq',$keyarr[0]);
    			$function = $ModuleFunction->alias("function")
    			->join("LEFT JOIN wx_".$cid."_material material on material.module=function.module")
    			->join("LEFT JOIN wx_".$cid."_material_keyword keyword on keyword.materialId=material.id")
    			->where($condition)
    			->field("function.*,material.name as fName,material.id as fId")
    			->find();
    			if ($function) {
    				Output::instance()->object($function);
    			} else {
    				Output::instance()->resultCode(code_success);
    			}
    		}else{
    			Output::instance()->resultCode(code_success);
    		}
    	}
    }
    
    /**
     * 不查询数据库获取返回信息
     * @param unknown_type $content
     * @param unknown_type $type
     */
    public function getModuleFunctionByTypeNotQuery($content,$type){
        /**
         * 20170713 - 这里这个model模型, 会被作为参数传到getCuserList函数中, 请看该函数内关于修改备注
         * LLyeap_wx_customer修改
         */
        /***** LLyeap_delete *****/
//    	$customer = D("Customer");
        /*****  *****/

        $IndMediaInfo_Model = D('ind_media_info');
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
        $queryParts = explode('&', $content);
    	$urlparams = array();
    	$paramsItems = array();
    	foreach ($queryParts as $param){
    		$item = explode('=', $param);
    		$urlparams[$item[0]] = $item[1];
    	}
    	$module = $urlparams['module'];
    	$params = $urlparams['params'];
    	$params = str_replace( array('%7B','%7D','%22'), array('','',''), $params);
    	$params = str_replace(array('{', '}', '"'), array('','',''), $params);
    	$queryParams = explode(',', $params);
    	foreach ($queryParams as $par) {
    		$item = explode(':', $par);
    		$paramsItems[$item[0]] = $item[1];
    	}
    	if($module){
   		 switch($module){
   		 		//显示管理员列表
    			case 'redEnvelope':
                    /***** LLyeap_delete *****/
//    				$result = $this->getCuserList($paramsItems['r'],$customer);
                    /*****  *****/

    				$result = $this->getCuserList($paramsItems['r'],$IndMediaInfo_Model);
    				break;
    		}
    		if (empty($result)) {
    			$result['fName'] = NULL;
    			$result['fId'] = NULL;
    		}
     		Output::instance()->object($result);
    	} else {
    		Output::instance()->resultCode(code_success);
    	}
    	
    	
    }
    
    private function getMaterialById($id){
    	$MaterialModel = D("Material");
    	
    	$wsCon["id"] = array('eq', $id);
    	$wsMaterial = $MaterialModel->where($wsCon)->find();
    	return $wsMaterial;
    	
    }
    
    
    private function getModuleMaterial($id) {
    	$function = array();
    	$material = $this->getMaterialById($id);
    	if ($material) {
    		$function["fName"] = $material["name"];
    		$function["fId"] = $id;
    	}
    	return $function;
    }
    

    /**
     * 获取模板账号(管理员)列表
     *
     * @param $id
     * @param $IndMediaInfo_Model
     * @return array
     */
    private function getCuserList($id,$IndMediaInfo_Model) {
        /** 这里由于是获得总的(就是default, 用户的)信息, 所以不需要mediaId */
        $function = array();
        $customerArr = $IndMediaInfo_Model->alias("imi")
            ->field("imi.id,cu.loginName")
            ->join("wx_customer_user cu ON  cu.customerId= imi.cid")
            ->where(['cu.id' => $id, 'imi.isDefault' => 1])
            ->find();
        if ($customerArr) {
            $function["fName"] = $customerArr["loginName"];
            $function["fId"] = $customerArr["id"];
        }
        return $function;
    }
    /***** LLyeap_delete *****/
//    private function getCuserList($id,$customer) {
//    	 $function = array();
//    	 $customerArr = $customer->alias("c")
//    	 ->field("c.id,cu.loginName")
//    	 ->join("wx_customer_user cu ON  cu.customerId= c.id")
//    	 ->where("cu.id=$id")
//    	 ->find();
//    	if ($customerArr) {
//    		$function["fName"] = $customerArr["loginName"];
//    		$function["fId"] = $customerArr["id"];
//    	}
//    	return $function;
//    }
    /*****  *****/

    
    private function getWebPage($method, $id) {
    	$function = array();
    	$WebPageModel = D("web_page");
    	switch ($method) {
    		case 'getWebPageTag'://获取文章标签列表
    			$TagModel = M("web_page_tag");
    			$wscon['id'] = array('eq',$id);
    			$webPageTag = $TagModel->where($wscon)->find();
    			if($webPageTag){
    				$function["fName"] = $webPageTag["tagName"];
    				$function["fId"] = $id;
    			}
    			break;
    		case 'getWebPage'://获取文章
		    	$wcon['id'] = array('eq',$id);
		    	$webPage = $WebPageModel->where($wcon)->find();
		    	if($webPage){
		    		$function["fName"] = $webPage["title"];
		    		$function["fId"] = $id;
		    	}
		    	break;
    	}
    	return $function;
    }
    
    
    private function getWebSite($method, $id) {
    	$function = array();
    	switch ($method) {
    		case 'getWebSiteTag'://获取文章标签列表
    			$TagModel = M("web_page_tag");
    			$wscon['id'] = array('eq',$id);
    			$webPageTag = $TagModel->where($wscon)->find();
    			if($webPageTag){
    				$function["fName"] = $webPageTag["tagName"];
    				$function["fId"] = $id;
    			}
    			break;
    		case 'getWebSite'://微网站
    			$wsMaterial = $this->getMaterialById($id);
    			if ($wsMaterial) {
    				$function["fName"] = $wsMaterial["name"];
    				$function["fId"] = $id;
    			}
    			break;
    	}

    	return $function;
    }
    
  
    private function getGreetingCard($method, $id) {
		$function = array();
    	switch ($method) {
    		case 'card'://获取贺卡
    			$customerId = Session::$user['customerId'];
    			Session::switchCustomer(0);
    									
    			$GreetingCardModel = M("greeting_card");
    			$cardCon['id'] = array('eq', $id);
    			$card = $TagModel->where($cardCon)->find();
  				if($card){
   					$function["fName"] = $card["name"];
 					$function["fId"] = $id;
 				}
   				Session::switchCustomer($customerId);
   				break;
    	}
    	return $function;
    }
    
    private function getExpertQA($method) {
    	$function = array();
    	switch ($method){
    		case 'postpage'://获取专家问答发表问题
    			$function["fName"] ='发表问题';
    			break;
    		case 'userpostpage'://获取专家问答问题列表
    			$function["fName"] ='问题列表';
    			break;
    	}
    	return $function;
    }
    
    private function getStore($method, $paramsItems) {
    	$function = array();
    	switch ($method){
    		case 'getStoreDistrict'://获取门店区域
    			$customerId = Session::$user["customerId"];
    			Session::switchCustomer(0);
    			 
    			$StoreModel = M("store_district_category");
    			$where["id"] = $paramsItems['districtCategoryId'];
    			$categoryName = $StoreModel->where($where)->getField("name");
    			$function["fName"] = $categoryName;
    			$function["fId"] = $paramsItems['districtCategoryId'];
    			Session::switchCustomer($customerId);
    			break;
    		case 'getStoreList'://门店列表
    			$customerId = Session::$user["customerId"];
    			Session::switchCustomer(0);
    	
    			$StoreModel = M("store");
    			$condition['store.districtId'] = array('eq',$paramsItems['id']);
    			$condition['store.deleted'] = array('eq',0);
    	
    			$districtName = $StoreModel->alias("store")->where($condition)
    			->join("wx_store_district dis ON dis.id=store.districtId")
    			->field("dis.name name")->find();
    			if ($districtName) {
	    			$function["fName"] = $districtName['name'];
	    			$function["fId"] = $paramsItems['id'];
    			}
    			Session::switchCustomer($customerId);
    			break;
    		case 'getStoreDetail':
    			$customerId = Session::$user["customerId"];
    			Session::switchCustomer(0);
    			 
    			$StoreModel = M("store");
    			$condition['id'] = array('eq',$paramsItems['id']);
    			$condition['deleted'] = array('eq',0);
    			 
    			$store = $StoreModel->where($condition)->field("name")->find();
    			if ($store) {
    				$function["fName"] = $store['name'];
    				$function["fId"] = $paramsItems['id'];
    			}
    			Session::switchCustomer($customerId);
    			break;
    	}
    	return $function;
    }
    
    private function getProduct($method, $paramsItems) {
    	$function = array();
    	switch ($method){
    		case 'getProductCategoryById'://获取产品类别列表
    			$ProductCatModel = M("module_product_category");
    			$pcCon["id"] = array('eq',$paramsItems['id']);
    			$pcat = $ProductCatModel->where($pcCon)->find();
 //     		Log::write($ProductCatModel->getLastSql());
    			if($pcat){
    				$function["fName"] = $pcat['name'] . "分组商品列表";
    				$function["fId"] = $paramsItems['id'];
    			}
    			break;
    		case 'getProduct'://获取产品
    			$ProductModel = M("module_product");
    			$where["id"] = array('eq',$paramsItems['id']);
    			$where["isRemoved"] = 0;
    			$where["deleted"] = 0;
    			$product = $ProductModel->where($where)->find();
    			if($product) {
    				$function["fName"] = $product['name'];
    				$function["fId"] = $paramsItems['id'];
    			}
    			break;
    		case 'getProductByTag':
    			if(isset($paramsItems['id'])){
    				$TagModel = D("module_product_tag");
    				$arrTag = explode(",", $paramsItems['id']);
    				$tagId = $arrTag[0];
    				$tag = $TagModel->where("id=$tagId")->find();
    				if ($tag) {
    					$function["fName"] =$tag['name'];
    					$function["fId"] = $paramsItems['id'];
    				}
    			}else if(isset($paramsItems['tagname'])){
    				$tagname = $paramsItems['tagname'];
    				$function["fName"] = $paramsItems['tagname'];
    				$TagModel = D("module_product_tag");
    				$tag = $TagModel->where("name=$tagname")->find();
    				if ($tag) {
    					$function["fName"] =$tag['name'];
    					$function["fId"] = $tag['id'];
    				}
    			}
    			break;
    	}
    	return $function;
    }
    
   
    
    private function getMember($method, $id) {
    	$function = array();
    	switch ($method){
    		case 'get'://获会员
    			$function["fName"] = "会员卡";
    			$function["fId"] = $id;
    			break;
    	}
    	return $function;
    }
    
    private function getEmployeeManage($method) {
    	$function = array();
    	switch ($method){
    		case 'manageSystem'://终端查询系统
    			$function["fName"] = "终端查询系统";
    			$function["fId"] = NULL;
    			break;
    	}
    	return $function;
    }
}